<template>
	<div class="system-menu-container">
		<div class="breadcrumb-box">
			<Breadcrumb />
		</div>

		<div class="header-search flex space-between">
			<div>
				<el-input class="search-item" placeholder="请输入术式名称或手术代码" v-model="state.apiData.search" size="default"
					style="width: 220px;" clearable @change="searchChange()">
				</el-input>
				<el-select v-model="state.apiData.departmentId" placeholder="请选择科室" size="default" clearable filterable
					@change="dpChange" style="width:200px;margin-right:20px;">
					<el-option v-for="(item, index) in state.departmentList" :key="index" :label="item.departmentName"
						:value="item.id"></el-option>
				</el-select>
				<el-select v-model="state.apiData.uid" placeholder="请选择医生" size="default" clearable filterable
					style="width:120px;margin-right:20px;">
					<el-option v-for="(item, index) in state.doctorList" :key="index" :label="item.name"
						:value="item.id"></el-option>
				</el-select>
				<el-button size="default" type="primary" @click="searchChange()" :icon="Search">查询</el-button>
				<el-button size="default" type="default" @click="resetSearch()" :icon="RefreshRight">重置</el-button>
			</div>

			<el-button size="default" type="primary" @click="checkAll()">{{ state.isAllCheck ? '取消全选' : '全选' }}</el-button>
		</div>

		<div class="page-main" v-loading="state.tableData.loading" ref="pageMain">
			<el-card shadow="hover" style="height:100%;">

				<div class="output-box flex">
					<el-button size="default" type="primary" style="width: 100px;" @click="downloadTemplate">
						模板下载
					</el-button>
					<el-upload ref="uploadRef" action="#" :http-request="uploadAction" :show-file-list="false"
						:before-upload="beforeUpload" :auto-upload="true" style="margin: 0 10px;">
						<el-button size="default" type="primary" v-loading="state.uploadLoading" style="width: 100px;">导入</el-button>
					</el-upload>

					<el-button size="default" type="primary" style="width: 100px;">
						准入记录
					</el-button>
				</div>

				<el-table :data="state.tableData.data" border style="width: 100%" :height="state.tableHeight"
					ref="multipleTableRef">
					<el-table-column label="序号" type="index" width="100" show-overflow-tooltip align="center"></el-table-column>
					<el-table-column prop="code" label="手术代码" show-overflow-tooltip align="center" width="150"></el-table-column>
					<el-table-column prop="name" label="手术名称" show-overflow-tooltip align="center"></el-table-column>
					<el-table-column prop="level" label="手术级别" show-overflow-tooltip align="center" width="100"></el-table-column>
					<el-table-column label="日间标志" align="center" width="100">
						<template #default="scope">
							<el-checkbox v-model="scope.row.isDaySign" @change="daySignChange(scope.row.id, scope.row.isDaySign)">
								{{ }}
							</el-checkbox>
						</template>
					</el-table-column>
					<!-- <el-table-column label="病区代码" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ scope.row.hospitalArea ? scope.row.hospitalArea.id : '-' }}
						</template>
					</el-table-column>
					<el-table-column label="病区名称" show-overflow-tooltip align="center">
						<template #default="scope">
							{{ scope.row.hospitalArea ? scope.row.hospitalArea.name : '-' }}
						</template>
					</el-table-column> -->
					<el-table-column label="科室" show-overflow-tooltip align="center" min-width="200">
						<template #default="scope">
							{{ scope.row.departmentStr }}
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="100">
						<template #default="scope">
							<el-button size="small" link type="primary" @click="editFun(scope.row)">修改</el-button>
						</template>
					</el-table-column>


				</el-table>


				<div class="pagination-box">
					<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
						:pager-count="5" :page-sizes="[10, 20, 30]" v-model:current-page="state.apiData.page" background
						v-model:page-size="state.apiData.pageSize" layout="total, sizes, prev, pager, next, jumper"
						:total="state.tableData.total">
					</el-pagination>
				</div>

			</el-card>
		</div>

		<DetailDialog ref="detailDialogRef" @refresh="getList()" />
	</div>
</template>

<script setup name="entryAndExit-operationEntry-index">
import { getCurrentInstance } from 'vue';
import { entryAndExitApi } from '/@/api/entryAndExit'
import { ElMessage } from 'element-plus';
import { toolsApi } from '/@/api/tools'
import { getHost } from "/@/utils/getHost";
import {
	Search,
	RefreshRight,
} from '@element-plus/icons-vue'
// 引入组件
const Breadcrumb = defineAsyncComponent(() => import('/@/layout/navBars/breadcrumb/breadcrumb.vue'));
const DetailDialog = defineAsyncComponent(() => import('./components/dialog.vue'));

const uploadRef = ref();
const detailDialogRef = ref();
// 定义变量内容
const state = reactive({
	apiData: {
		page: 1,
		pageSize: 10,
		search: '',
		departmentId: '',
		uid: ''
	},
	tableData: {
		data: [],
		loading: false,
		total: 0
	},
	tableHeight: '30vh',
	uploadLoading: false,
	departmentList: [],
	doctorApiData: {
		departmentId: null
	},
	doctorList: [],
	isAllCheck: false
});

// 页面加载时
onMounted(() => {
	getDepatment()
	getList()
	getDoctors()
	state.tableHeight = getCurrentInstance().refs.pageMain.offsetHeight - 130 - 52 + "px";
});

const searchChange = () => {
	state.apiData.page = 1
	getList()
}



// 分页改变
const onHandleSizeChange = (val) => {
	state.apiData.pageSize = val;
	getList();
};
const onHandleCurrentChange = (val) => {
	state.apiData.page = val;
	getList();
};



const resetSearch = () => {
	state.apiData = {
		page: 1,
		pageSize: 10,
		name: '',
	},
		getList()
}

const editFun = (row) => {
	detailDialogRef.value.openDialog(row);
}


const downloadTemplate = () => {
	const url =  getHost() + '/operation_admission/importTemplate'
	const link = document.createElement('a')
	link.href = url
	link.setAttribute('download', '')
	document.body.appendChild(link)
	link.click()
	document.body.removeChild(link)
}


// 获取列表
const getList = () => {
	state.tableData.loading = true
	entryAndExitApi().operationAccessList(state.apiData).then(res => {
		state.tableData.loading = false
		let checkedIdList = []
		res.data.items.forEach(item => {
			const departmentNameList = []
			if (item.isDaySign ) {
				checkedIdList.push(item.id)
			}
			item.department.forEach(it => {
				departmentNameList.push(it.departmentName + '(' + it.departmentNo + ')')
			})
			item.departmentStr = departmentNameList.length ? departmentNameList.join(',') : '-'
		})
		if (checkedIdList.length == res.data.items.length) {
			state.isAllCheck = true
		} else {
			state.isAllCheck = false
		}
		state.tableData.data = res.data.items
		state.tableData.total = res.data.total
	}).catch(() => {
		state.tableData.loading = false
	})

}

const uploadAction = (option) => {
	state.uploadLoading = true
	console.log(option)
	const formData = new FormData()
	formData.append('file', option.file);
	entryAndExitApi().importOperation(formData).then(res => {
		state.uploadLoading = false
		ElMessage.success('上传成功');
		getList()
	}).catch(() => {
		state.uploadLoading = false
		ElMessage.error('上传失败');
	})
}

const beforeUpload = (rawFile) => {
	console.log('rawFile', rawFile)
	const localName = rawFile.name;
	const suffix = localName
		.substring(localName.lastIndexOf("."))
		.toLowerCase();
	if ([".xls", ".xlsx"].indexOf(
		suffix
	) === -1) {
		ElMessage.error('请上传xls或xlsx文件')
		return false
	}
	return true
}

// 获取科室
const getDepatment = () => {
	toolsApi().departmentList().then(res => {
		state.departmentList = res.data
	})
}

const daySignChange = (id, val) => {
	const apiData = {
		operationIds: [id],
		isDaySign: val
	}
	entryAndExitApi().operationSetIsDaySign(apiData).then(res => {
		getList()
	})
}

const checkAll = () => {
	const allIdList = []
	state.tableData.data.forEach(item => {
		allIdList.push(item.id)
	})

	const apiData = {
		operationIds: allIdList,
		isDaySign: state.isAllCheck ? false : true
	}
	entryAndExitApi().operationSetIsDaySign(apiData).then(res => {
		getList()
	})
}

const dpChange = (e) => {
	if (e) {
		state.doctorApiData.departmentId = e
	} else {
		state.doctorApiData.departmentId = null
	}
	getDoctors()
}

const getDoctors = () => {
	toolsApi().doctorList(state.doctorApiData).then(res => {
		state.doctorList = res.data
	})
}

</script>

<style lang="scss" scoped>
.el-checkbox.el-checkbox--large {
	height: 32px !important;
}

.page-main {
	height: calc(100vh - 50px - 106px);
}




.output-box {
	margin-bottom: 20px;
}
</style>
